package com.jincheng.springblog.controller;

import com.jincheng.springblog.constant.Constants;
import com.jincheng.springblog.model.BlogInfo;
import java.util.List;

import com.jincheng.springblog.service.BlogService;
import com.jincheng.springblog.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController {

    @Autowired
    private BlogService blogService;

    @RequestMapping(value = "/getList")
    public List<BlogInfo> getList(){
        return blogService.getList();
    }

    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request){
        BlogInfo blogDetail = blogService.getBlogDetail(blogId);
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId = JwtUtils.getIdByToken(token);
        if(userId != null && userId == blogDetail.getUserId()){
            blogDetail.setLoginUser(true);
        }else{
            blogDetail.setLoginUser(false);
        }
        return blogDetail;
    }

    @RequestMapping("/add")
    public Boolean addBook(@RequestBody BlogInfo blogInfo, HttpServletRequest request){
       log.info("添加图书，blogInfo:{}",blogInfo);
       if(!StringUtils.hasLength(blogInfo.getTitle()) || !StringUtils.hasLength(blogInfo.getContent())){
           return false;
       }
       String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
       Integer userId = JwtUtils.getIdByToken(token);
       if(userId == null || userId <= 0){
           return false;
       }
       blogInfo.setUserId(userId);
       return blogService.insertBook(blogInfo);
    }

    @RequestMapping("/update")
    public Boolean update(BlogInfo blogInfo){
        if(blogInfo.getId() == null || !StringUtils.hasLength(blogInfo.getTitle()) || !StringUtils.hasLength(blogInfo.getContent())){
            return false;
        }
        blogService.update(blogInfo);
        return true;
    }

    @RequestMapping("/delete")
    public Boolean delete(Integer blogId){
        if(blogId <= 0){
            return false;
        }
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);
        blogService.update(blogInfo);
        return true;
    }






















}
